<template>
  <el-dialog v-if="load" :close-on-click-modal="false" :title="form.e_id ? '修改' : '添加'" v-model="visible" align-center :z-index="2000"
    width="500px" @close="handleClose">
    <el-form ref="formRef" :model="form" label-position="top">
      <el-form-item label="采购人员" prop="purchase_user_id"
        :rules="[{ required: true, message: '不能为空', trigger: 'change' }]">
        <VCascader v-if="visible" v-model="form.purchase_user_id" placeholder="采购人员" filterable clearable class="w-full"
          @change="userChange" />
      </el-form-item>
      <div class="grid grid-cols-7 gap-x-3">
        <el-form-item label="使用邮箱" prop="account"
          :rules="[{ required: true, message: '未获取到邮箱，请到飞书配置', trigger: 'change' }]" class="col-span-6">
          <el-input v-model="form.account" disabled placeholder="使用邮箱" class="w-full" />
        </el-form-item>
        <el-form-item label="状态">
          <el-switch v-model="form.status" :active-value="1" inline-prompt active-text="启用" inactive-text="禁用"
            :inactive-value="2">
          </el-switch>
        </el-form-item>
      </div>
      <el-form-item label="邮箱密码" prop="password" :rules="[{ required: true, message: '不能为空', trigger: 'blur' }]">
        <el-input v-model="form.password" placeholder="邮箱密码" class="w-full" />
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="close">取 消</el-button>
      <el-button type="primary" :loading="loadings.submit" @click="submit">确 定</el-button>
    </template>
  </el-dialog>
</template>

<script setup>
import { nextTick } from 'vue';
import api from '../api'
import { getUserEmail } from '@/api/public'
import { ElMessage } from 'element-plus'
const load = ref(false)
const visible = ref(false)
let loadings = reactive({})
const form = ref({})
const formRef = ref()

const emit = defineEmits(['close', 'success'])

const userChange = ({ value }) => {
  getUserEmail({ user_id: value }).then(res => {
    form.value.account = res.data.email
  })
}

// 打开弹窗
const open = async (e_id) => {
  if (!load.value) {
    load.value = true
    await 1
  }
  loadings = reactive({})
  form.value = { status: 1 }
  visible.value = true
  formRef?.value?.resetFields()
  if (e_id) {
    const res = await api.detail({ e_id })
    form.value = res.data
  }
}
// 关闭弹窗
const close = () => {
  visible.value = false
}

const handleClose = () => {
  emit('close')
}
// 提交
const submit = async () => {
  const validator = await formRef?.value.validate()
  if (!validator) return
  loadings.submit = true
  api[form.value.e_id ? 'update' : 'add'](form.value).then(res => {
    ElMessage.success('操作成功')
    emit('success')
    close()
  }).finally(() => {
    loadings.submit = false
  })
}

defineExpose({ open })
</script>